<template>
  <div class="order-confirm">
    <!-- 导航栏 -->
    <van-nav-bar
      fixed
      title="订单确认"
      left-arrow
      @click-left="$router.back()"
    />
    <van-cell-group>
      <!-- 收货地址 -->
      <van-cell is-link @click="addressShow = true">
        <reap-address :address="currentAddress" v-if="showStatus"/>
      </van-cell>
      <!-- 店铺信息 -->
      <van-cell>
        <shop-item :shopId="$route.params.shopId"/>
      </van-cell>
      <!-- 选中的商品 -->
      <van-cell>
        <van-card
          v-for="(item,i) in goodsList"
          :key="i"
          :thumb="item.goods_image"
          :title="item.goodsname"
          :num="item.goods_amount"
          :price="item.goods_price"
        >
        </van-card>
      </van-cell>
      <!-- 活动优惠项 -->
      <van-cell title="活动优惠" is-link @click="activetShow = true"></van-cell>
      <!-- 优惠券 -->
      <van-cell title="优惠券" is-link @click="discountShow = true"></van-cell>
      <!-- 配送方式 -->
      <van-cell title="配送方式/费用" is-link @click="deliveryShow = true"></van-cell>
      <!-- 合计 -->
      <van-cell>
        <div class="total-price">
          <span>合计</span>
          <span>￥ {{totalPrice}}</span>
        </div>
      </van-cell>
    </van-cell-group>
    <van-button
      color="#f93e2e"
      class="payBtn"
      @click="orderConfirm"
    >确认并支付(微信支付)</van-button>
    <!-- 配送方式列表弹窗 -->
    <van-popup v-model="deliveryShow" position="bottom" :style="{ height: '30%' }">
      <!-- <van-picker
        title="标题"
        show-toolbar
        :columns="columns"
        @confirm="onConfirm"
        @cancel="onCancel"
        @change="onChange"
      /> -->
      配送方式
    </van-popup>
    <!-- 收货地址列表弹窗 -->
    <van-popup v-model="addressShow" position="bottom" :style="{ height: '100%' }">
      <van-nav-bar
        fixed
        title="选择收获地址"
        left-arrow
        @click-left="addressShow=false"
      />
      <!-- 占位元素 -->
      <div :style="{ height: '35px' }"></div>
      <van-address-list
        v-model="chosenAddressId"
        :list="addressList"
        default-tag-text="默认"
        @add="onAddAddress"
        @edit="onEditAddress"
      />
    </van-popup>
    <!-- 优惠券列表弹窗 -->
    <van-popup v-model="discountShow" position="bottom" :style="{ height: '30%' }">
      优惠券列表
    </van-popup>
    <!-- 活动列表弹窗 -->
    <van-popup v-model="activetShow" position="bottom" :style="{ height: '40%' }">
      活动列表
    </van-popup>
    <!-- 编辑地址弹窗 -->
    <van-popup v-model="editAddressShow" position="bottom" :style="{ height: '100%' }">
      <van-nav-bar
        fixed
        :title="`${editAddressType?'添加':'编辑'}收货地址`"
        left-arrow
        @click-left="editAddressShow = false"
      />
      <!-- 占位元素 -->
      <div :style="{ height: '35px' }"></div>
      <van-address-edit
        :address-info="infoAddress"
        v-if="editAddressShow"
        :area-list="areaList"
        :show-delete="!editAddressType"
        show-set-default
        :area-columns-placeholder="['请选择', '请选择', '请选择']"
        @save="editAddress"
        @delete="deleteAddress"
      />
    </van-popup>
  </div>
</template>

<script>
import ReapAddress from '@/components/reap-address'
import ShopItem from './components/shop-item'
import { mapState } from 'vuex'
import {
  editAddressReq,
  deleteAddressReq,
  addAddress,
  addOrder,
  getDelivery,
  getReceiveAddressList
  // getDiscountList
  // getActivetList
} from '@/api/order'
import areaList from '@/assets/areaAddress'
export default {
  name: 'OrderConfirm',
  components: {
    ReapAddress,
    ShopItem
  },
  props: {
    // goods: {
    //   type: Array
    //   // required: true
    // },
    // shopId: {
    //   type: [Number, String],
    //   // required: true
    //   default: 1
    // }
  },
  data () {
    return {
      // 数据获取状态
      showStatus: false,
      // 配送方式弹窗开关
      deliveryShow: false,
      // 收货地址列表弹窗开关
      addressShow: false,
      // 编辑地址弹窗开关
      editAddressShow: false,
      // 编辑地址弹窗类型（新增、修改）
      editAddressType: true,
      // 编辑地址弹窗初始值
      infoAddress: {},
      // 优惠券列表弹窗开关
      discountShow: false,
      // 活动列表弹窗开关
      activetShow: false,
      // 地址列表
      addressList: [
      ],
      // 配送方式列表
      deliveryList: [],
      // 当前选中的地址Id
      chosenAddressId: 0,
      // 全国地址列表
      areaList
    }
  },
  computed: {
    totalPrice() {
      let totalPrice = 0
      this.goodsList.forEach(item => {
        totalPrice += item.goods_amount * item.goods_price
      })
      return totalPrice
    },
    currentAddress() {
      return this.addressList.find(item =>
        item.id === this.chosenAddressId
      )
    },
    ...mapState(['goodsList'])

  },
  created () {
    this.init()
  },
  mounted () {

  },
  methods: {
    // 删除地址
    async deleteAddress(address) {
      const { data: res } = await deleteAddressReq(address.id)
      console.log(res)
      this.$toast(res.meta.msg)
      if (res.meta.status !== 200) return
      // 更新地址列表
      this.editAddressShow = false
      this.addressList = []
      this.showStatus = false
      this.init()
      // if (res.meta.status !== 200) return this.$toast(res.meta.msg)
    },
    // 提交地址，更改或新增
    async editAddress(address) {
      // 将省市区拼接一个字符串
      const addressStr = `${address.province}  ${address.city}  ${address.county}  ${address.addressDetail}`
      // 新增地址
      if (this.editAddressType) {
        const { data: res } = await addAddress({
          receive_user_name: address.name,
          receive_user_gender: 'male',
          receive_user_phone: address.tel,
          receive_user_address: addressStr,
          receive_address_tag: 'company',
          is_default: address.isDefault ? 'yes' : 'no'
        })
        this.$toast(res.meta.msg)
      } else {
        // 编辑地址
        const { data: res } = await editAddressReq(address.id, {
          receive_user_name: address.name,
          receive_user_phone: address.tel,
          receive_user_address: addressStr,
          is_default: address.isDefault ? 'yes' : 'no'
        })
        this.$toast(res.meta.msg)
      }
      // 更新地址列表
      this.editAddressShow = false
      this.addressList = []
      this.showStatus = false
      this.init()
    },
    // 确认订单，提交
    async orderConfirm() {
      const list = []
      this.goodsList.forEach(item => {
        list.push({
          goods_id: item.goods_id,
          goods_amount: item.goods_amount,
          goods_price: item.goods_price
        })
      })
      const { data: res } = await addOrder({
        shop_id: this.$route.params.shopId,
        goodsList: list,
        order_money: this.totalPrice,
        receive_address_id: this.chosenAddressId,
        delivery_id: 2,
        delivery_money: 52,
        packing: 2 // 包装费
      })
      if (res.meta.status !== 200) return this.$toast(res.meta.msg)
      this.$toast('购买成功')
      this.$store.commit('setGoodsList', [])
      this.$router.back()
    },
    // 映射地址列表
    mapAddress(arr) {
      arr.forEach((item, i) => {
        if (i === 0 || item.is_default === 'yes') {
          this.chosenAddressId = item.receive_address_id
          this.addressList.unshift({
            id: item.receive_address_id,
            name: item.receive_user_name,
            tel: item.receive_user_phone,
            address: item.receive_user_address,
            isDefault: item.is_default === 'yes'
          })
          return
        }
        this.addressList.push({
          id: item.receive_address_id,
          name: item.receive_user_name,
          tel: item.receive_user_phone,
          address: item.receive_user_address,
          isDefault: item.is_default === 'yes'
        })
      })
    },
    // 触发编辑地址
    onEditAddress(item, index) {
      // item: 地址对象，index: 索引
      this.editAddressType = false
      this.infoAddress = {
        id: item.id,
        isDefault: item.isDefault,
        name: item.name,
        tel: item.tel,
        addressDetail: item.address
      }
      this.editAddressShow = true
    },
    // 触发新增地址
    onAddAddress() {
      this.editAddressType = true
      this.infoAddress = {}
      this.editAddressShow = true
    },
    // 初始化订单选项
    async init() {
      try {
        // 获取配送方式
        const { data: deliveryRes } = await getDelivery(this.shopId)
        console.log(deliveryRes)
        this.deliveryList = deliveryRes.data
        // 获取收货地址列表
        const { data: receiveAddressRes } = await getReceiveAddressList()
        // console.log(receiveAddressRes)
        this.mapAddress(receiveAddressRes.data)
        // 获取优惠券列表
        // const { data: discountRes } = await getDiscountList()
        // console.log(discountRes)
        // 获取活动列表
        // const { data: activetRes } = await getActivetList(this.shopId)
        // console.log(activetRes)
      } catch (error) {
        this.$toast('获取选项信息失败')
      }
      this.showStatus = true
    }
  }
}
</script>

<style scoped lang="less">
.order-confirm {
  padding: 85px 0;
  .van-nav-bar {
    background: #f93e2e;
  }
  .total-price {
    display: flex;
    justify-content: space-between;
    padding-right: 20px;
  }
  .payBtn {
    width: 100%;
    position: fixed;
    bottom: 0;
  }
}
/deep/.van-nav-bar__title{
  color: #fff
}
/deep/.van-icon-arrow-left {
  color:#fff
}
</style>
